<template>
  <div class="page-controller">
    <TModuleForm isShowHeader class="TModuleForm" ref="sourceForm" titleBold :formOpts="formOpts">
      <template #csbzjsfkzh>
        <el-input v-model="formOpts.opts.formData.csbzjsfkzh">
          <!-- <template #append>
                <el-button @click="extractBalance">提取核心余额</el-button>
              </template> -->
        </el-input>
      </template>
      <template #gxhtczzje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.gxhtczzje"
          v-model="formOpts.basicInfo.opts.formData.gxhtczzje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #htje>
        <!-- <el-input
                v-if="sqlx!='1200'"
                v-thousandSeparator="formOpts.basicInfo.opts.formData.htje"
                v-model="formOpts.basicInfo.opts.formData.htje"
                placeholder=""
                :disabled="true"
              ></el-input>
              <el-input
                v-else
                v-thousandSeparator="formOpts.paymentInfo.opts.formData.htje"
                v-model="formOpts.paymentInfo.opts.formData.htje"
                placeholder=""
                :disabled="true"
              ></el-input> -->
      </template>
      <template #zyhxqyed>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.zyhxqyed"
          v-model="formOpts.basicInfo.opts.formData.zyhxqyed"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #bbck>
        <el-input v-model="formOpts.basicInfo.opts.formData.bbck" placeholder="" :disabled="true"></el-input>
      </template>
      <template #cckye>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.cckye"
          v-model.number="formOpts.basicInfo.opts.formData.cckye"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #krzje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.krzje"
          v-model="formOpts.basicInfo.opts.formData.krzje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #yszkzje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.yszkzje"
          v-model="formOpts.basicInfo.opts.formData.yszkzje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #chkbzjje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.chkbzjje"
          v-model="formOpts.basicInfo.opts.formData.chkbzjje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #zhtje>
        <el-input v-model="formOpts.basicInfo.opts.formData.zhtje" placeholder="" :disabled="true"></el-input>
        <!-- <el-input
            v-if="route.query.sqlx!='8500'"
            v-model="formOpts.basicInfo.opts.formData.zhtje"
            placeholder=""
            :disabled="true"
          ></el-input>
          <el-input
            v-else
            v-thousandSeparator="formOpts.contractInfo.opts.formData.zhtje"
            v-model="formOpts.contractInfo.opts.formData.zhtje"
            placeholder=""
            :disabled="true"
            ></el-input>  -->
      </template>
      <template #yfkje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.yfkje"
          v-model="formOpts.basicInfo.opts.formData.yfkje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #cyszkzje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.cyszkzje"
          v-model.number="formOpts.basicInfo.opts.formData.cyszkzje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #chkbzjye>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.chkbzjye"
          v-model.number="formOpts.basicInfo.opts.formData.chkbzjye"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #hkbzjzhkjye>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.hkbzjzhkjye"
          v-model.number="formOpts.basicInfo.opts.formData.hkbzjzhkjye"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #kzyje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.kzyje"
          v-model.number="formOpts.basicInfo.opts.formData.kzyje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #zcje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.zcje"
          v-model.number="formOpts.basicInfo.opts.formData.zcje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #fxck>
        <el-input
          v-thousandSeparator="formOpts.paymentInfo.opts.formData.fxck"
          v-model.number="formOpts.paymentInfo.opts.formData.fxck"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #ljthje>
        <!-- <el-input
            v-if="route.query.sqlx!='1300'"
            v-thousandSeparator="formOpts.applicationInfo.opts.formData.ljthje"
            v-model.number="formOpts.applicationInfo.opts.formData.ljthje"
            placeholder=""
            :disabled="true"
            ></el-input>
          <el-input
            v-else
            v-thousandSeparator="formOpts.basicInfo.opts.formData.htje"
            v-model.number="formOpts.basicInfo.opts.formData.ljthje"
            placeholder=""
            :disabled="true"
          ></el-input> -->
      </template>
      <template #bckthje>
        <el-input
          v-thousandSeparator="formOpts.applicationInfo.opts.formData.bckthje"
          v-model.number="formOpts.applicationInfo.opts.formData.bckthje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #bcsqje>
        <el-input
          v-thousandSeparator="formOpts.applicationInfo.opts.formData.bcsqje"
          v-model.number="formOpts.applicationInfo.opts.formData.bcsqje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #csbzjje>
        <!-- <el-input
            v-if="route.query.sqlx!='1200'"
            v-thousandSeparator="formOpts.basicInfo.opts.formData.csbzjje"
            v-model.number="formOpts.basicInfo.opts.formData.csbzjje"
            placeholder=""
            :disabled="true"
            ></el-input>
            <el-input
              v-else
              v-thousandSeparator="formOpts.applicationInfo.opts.formData.csbzjje"
              v-model.number="formOpts.applicationInfo.opts.formData.csbzjje"
              placeholder=""
              :disabled="true"
              ></el-input> -->
      </template>
      <template #zjbzjze>
        <el-input
          v-thousandSeparator="formOpts.applicationInfo.opts.formData.zjbzjze"
          v-model.number="formOpts.applicationInfo.opts.formData.zjbzjze"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #bchkje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.bchkje"
          v-model.number="formOpts.basicInfo.opts.formData.bchkje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #bczrpmje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.bczrpmje"
          v-model.number="formOpts.basicInfo.opts.formData.bczrpmje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #blfje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.blfje"
          v-model.number="formOpts.basicInfo.opts.formData.blfje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #qtfy>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.qtfy"
          v-model.number="formOpts.basicInfo.opts.formData.qtfy"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #ssfy>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.ssfy"
          v-model.number="formOpts.basicInfo.opts.formData.ssfy"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #ljskqrje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.ljskqrje"
          v-model.number="formOpts.basicInfo.opts.formData.ljskqrje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #sythje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.sythje"
          v-model.number="formOpts.basicInfo.opts.formData.sythje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #ckcetkje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.ckcetkje"
          v-model.number="formOpts.basicInfo.opts.formData.ckcetkje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #cetkje>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.cetkje"
          v-model.number="formOpts.basicInfo.opts.formData.cetkje"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #pjzsjz>
        <el-input
          v-thousandSeparator="formOpts.basicInfo.opts.formData.pjzsjz"
          v-model.number="formOpts.basicInfo.opts.formData.pjzsjz"
          placeholder=""
          :disabled="true"
        ></el-input>
      </template>
      <template #accountsReceivable>
        <FITable
          ref="tableRef"
          class="box-radius2 margin-top20"
          title="记录集"
          :id="`result_${tableId}`"
          :readonly="false"
          :data="state.dataList"
          primaryKey="formId"
          v-model:columns="columns"
          :isLoading="isTableLoading"
          insertable
          :saveSuccessful="saveSuccessful"
          :pageConfig="pageConfig"
          @row-add-save="addRowSave"
          @table-refresh="searchFn"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-page-change="handleCurrentChange"
          @action-click="handleAction"
        >
          <template #moduleEname1="{ scope }">
            <FISelect
              @change="onCellChange"
              v-if="scope.row.isSelected"
              v-model="scope.row.moduleEname1"
              valueCustom="value"
              :options="arr3"
              clearable
            />
            <span v-else>{{ scope.row.moduleEname1 }}</span>
          </template>

          <!-- <template #moduleEname1="{scope}">
            <FISelect
              v-if="scope.row.isSelected"
              @change="handleChange"
              v-model="scope.row.moduleEname1"
              valueCustom="value"
              :options="scope.row.moduleEname1Options"
              clearable
            />
   <span v-else>{{ scope.row.moduleEname1}} </span>
</template> -->

          <template #moduleEname2="{ scope }">
            <!-- {{ scope.row.moduleEname2 }} -->
            <!-- {{scope.row.moduleEname1Options}} -->

            <FISelect
              v-if="scope.row.isSelected"
              v-model="scope.row.moduleEname2"
              valueCustom="value"
              :options="scope.row.moduleEname1Options"
              clearable
            />
            <!-- <el-select
            v-if="scope.row.isSelected"
    v-model="scope.row.moduleEname2"
    :empty-values="[null, undefined]"
    :value-on-clear="null"
    clearable
    placeholder="Select"
    style="width: 240px"
   
  >
    <el-option
      v-for="item in scope.row.moduleEname2ptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select> -->
            <span v-else>{{ scope.row.moduleEname2 }} </span>
          </template>
          <template #iconInfo="{ scope }">
            <!-- <FISelect
              
              v-if="scope.row.isSelected"
              v-model="scope.row.formParam"
              valueCustom="value"
              :options="arr4"
              clearable
            />
   <span v-else>{{ scope.row.formParam}}</span> -->
            <FIIconInput v-if="scope.row.isSelected" v-model="scope.row.iconInfo"></FIIconInput>
            <span v-else>{{ scope.row.iconInfo }}</span>
          </template>
          <template #headerBtn>
            <FIPopconfirmBtn
              title="您是否确认添加数据吗？"
              buttonText="添加凭证"
              beforePopText="请选择一条数据"
              :btn-binds="{ customType: 'border', prefixIcon: 'icon-shanchu' }"
              :isVisible="!!checkedRows.length"
              @confirm="deleteRow1"
            >
            </FIPopconfirmBtn>
            <FIPopconfirmBtn
              title="您是否确认删除选中数据吗？"
              buttonText="删除凭证"
              beforePopText="请选择一条数据"
              :btn-binds="{ customType: 'border', prefixIcon: 'icon-shanchu' }"
              :isVisible="!!checkedRows.length"
              @confirm="deleteRow"
            >
            </FIPopconfirmBtn>
            <!-- <FIButton id="b5555"></FIButton> -->
          </template>
          <!-- <template #formCname>
        <el-table-column label="slot" align="center"> 22</el-table-column>
      </template> -->
        </FITable>
      </template>
    </TModuleForm>
    <assign-post
      ref="childComponent"
      :postShow="postShow"
      @update:postShow="(newValue) => (postShow = newValue)"
      :editData="selectedNode"
      @refresh="refreshTable"
    ></assign-post>
  </div>
</template>
<script setup lang="ts">
import assignPost from './assignPost.vue'
import TModuleForm from '@/components/module-form/index.vue'
import { reactive, onMounted, ref, computed, inject } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiGetfrontPrjMaint, apiGetlistAllModule1, apiGetModule2 } from '@/api/configEnvMaint/index.ts'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import FIIconInput from '@/components/FIIconInput.vue'
// 获取ref
const sourceForm: any = ref<HTMLElement | null>(null)
// 第一种：获取最终form表单数据

const formOpts: any = reactive({
  basicInfo: {
    title: '基本信息',
    name: 'basicInfo',
    widthSize: 3,
    ref: null,
    opts: {
      span: 8,
      formData: {
        ysjzlsh: null,
        xydm: null,
        xybh: null,
        mfmc2: null,
        ywpz: null,
        hbzl: null,
        yszkzje: null,
        rzbl: null,
        bzjzh: null,
        hkbzjye: null,
        pjzsjz: null,
        ckye: null,
        bs: null,
        sqje: null,
        jzrq: null,
        zt: null,
        cjr: null,
        cjsj: null,
        cjrssjg: null,
        zhxgr: null,
        zhxgsj: null,
        zhxgrssjg: null,
        yszkDjLsbs: [],
      },
      fieldList: [
        {
          label: '减值代码',
          value: 'ysjzlsh',
          type: 'input',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
        },
        {
          label: '保理合同代码',
          value: 'xydm',
          type: 'input',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
          labelPosition: 'right',
        },
        {
          label: '保理池合同编号',
          value: 'xybh',
          type: 'input',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
          labelPosition: 'right',
        },
        {
          label: '卖方名称',
          value: 'mfmc1',
          type: 'input',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
        },
        {
          label: '业务品种',
          value: 'ywpz',
          type: 'select-arr',
          comp: 'el-select',
          list: 'TFS_BLC_YWPZ',
          bind: {
            disabled: true,
          },
          labelPosition: 'right',
        },
        {
          label: '货币种类',
          value: 'hbzl',
          type: 'select-arr',
          comp: 'el-select',
          list: 'TFS_Currency',
          bind: {
            disabled: true,
          },
          labelPosition: 'right',
        },
        {
          label: '应收账款总净额(元)',
          value: 'yszkzje',
          type: 'input',
          comp: 'el-input',
          slotName: 'yszkzje',
          bind: {
            disabled: true,
          },
        },
        {
          label: '融资比例/支付对价比例（%）',
          value: 'rzbl',
          type: 'input',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
        },
        {
          label: '回款保证金账号',
          value: 'bzjzh',
          type: 'input',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
          labelPosition: 'right',
        },
        {
          label: '回款保证金余额(元)',
          value: 'hkbzjye',
          type: 'input',
          slotName: 'hkbzjye',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
        },
        {
          label: '票据折算价值(元)',
          value: 'pjzsjz',
          type: 'input',
          comp: 'el-input',
          slotName: 'pjzsjz',
          bind: {
            disabled: true,
          },
        },
        {
          label: '敞口余额(元)',
          value: 'ckye',
          type: 'input',
          comp: 'el-input',
          slotName: 'ckye',
          bind: {
            disabled: true,
          },
        },
        {
          label: '本次减值笔数',
          value: 'bs',
          type: 'input',
          comp: 'el-input',
          bind: {
            disabled: true,
          },
        },
        {
          label: '本次减值总金额(元)',
          value: 'sqje',
          type: 'input',
          comp: 'el-input',
          slotName: 'sqje',
          bind: {
            disabled: true,
          },
        },
        {
          label: '减值日期',
          value: 'jzrq',
          type: 'date',
          comp: 'el-date-picker',
          bind: {
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
          },
        },
        {
          label: '记录状态',
          value: 'zt',
          type: 'select-arr',
          comp: 'el-select',
          list: 'XYGL_BXXYZT',
        },
      ],
      rules: {
        jzrq: [{ required: true, message: '此为必填项', trigger: 'blur' }],
      },
      optionsKeys: [
        { key: 'TFS_Currency', listKey: 'TFS_Currency', type: '', name: '货币种类' },
        { key: 'XYGL_BXXYZT', listKey: 'XYGL_BXXYZT', type: '', name: '记录状态' },
        { key: 'TFS_BLC_YWPZ', listKey: 'TFS_BLC_YWPZ', type: '', name: '业务品种' },
      ],
      // 相关列表
      listTypeInfo: { user: {}, dept: {} },
    },
  },
  commonInfo: {
    title: '其他信息',
    name: 'commonInfo',
    widthSize: 2,
    opts: {
      span: 8,
      formData: {
        cjr: null,
        cjsj: null,
        cjrssjg: null,
        zhxgr: null,
        zhxgsj: null,
        zhxgrssjg: null,
      },
      fieldList: [
        {
          label: '创建人',
          value: 'cjr',
          type: 'select-arr',
          comp: 'el-select',
          list: 'cjrList',
          arrLabel: 'label',
          arrKey: 'value',
          bind: { disabled: true },
        },
        {
          label: '最后修改人',
          value: 'zhxgr',
          type: 'input',
          comp: 'el-input',
          bind: { disabled: true },
          labelPosition: 'right',
        },
        {
          label: '创建时间',
          comp: 'el-date-picker',
          value: 'cjsj',
          type: 'date',
          bind: { disabled: true },
          labelPosition: 'right',
        },
        {
          label: '最后修改时间',
          comp: 'el-date-picker',
          value: 'zhxgsj',
          type: 'date',
          bind: { disabled: true },
        },
        {
          label: '创建机构',
          value: 'cjrssjg',
          type: 'select-arr',
          comp: 'el-select',
          list: 'cjjgList',
          arrLabel: 'label',
          arrKey: 'value',
          bind: { disabled: true },
          labelPosition: 'right',
        },
        {
          label: '最后修改机构',
          value: 'zhxgrssjg',
          type: 'select-arr',
          comp: 'el-select',
          list: 'zhxgjgList',
          arrLabel: 'label',
          arrKey: 'value',
          bind: { disabled: true },
          labelPosition: 'right',
        },
      ],
    },
    listTypeInfo: {},
  },
  accountsReceivable: {
    title: '应收账款信减值清单',
    name: 'accountsReceivable',
    slotName: 'accountsReceivable',
  },
})
const route = useRoute()
const postShow = ref(false)
const searchWrapperSpan = 8
const isTableLoading = ref(false)
// 页面编码
const tableId = 'pageMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const state = reactive({
  query: {
    formEname: '',
    formCname: '',
    projectEname: '',
    moduleEname1: '',
    moduleEname2: '',
    isAuth: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  {
    label: '商务合同号',
    prop: 'formEname',
    align: 'center',
    width: '140',
    queryName: '',
    editable: true,
    // sortable: true,
    // filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { formEname: [{ required: true }] },
    },
  },
  {
    label: '卖方名称',
    prop: 'formCname',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    width: '150',
    editType: 'input',
    editable: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { formCname: [{ required: true }] },
    },
  },
  {
    label: '凭证类型',
    prop: 'formLoadPath',
    align: 'center',
    width: '180',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    // sortable: true,
    sortValue: '',
  },
  {
    label: '凭证号码',
    prop: 'moduleEname1',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editConfig: {
      rules: { moduleEname1: [{ required: true }] },
    },
  },
  {
    label: '凭证日期',
    prop: 'moduleEname2',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
  },
  {
    label: '凭证参数日期',
    prop: 'formParam',
    align: 'center',
    width: '150',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
  },
  {
    label: '最迟付款日',
    prop: 'iconInfo',
    align: 'center',
    width: '130',
    editType: 'input',
  },
  {
    label: '凭证金额',
    prop: 'isAuth',
    align: 'center',
    width: '130',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    editConfig: {
      rules: { isAuth: [{ required: true }] },
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },

  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    width: '160',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '操作',
  //   prop: 'action',
  //   actionConfig: [
  //     { id: 'delete', type: 'delete' },
  //     { id: 'b5555', type: 'add' },
  //   ],
  // },
])

const checkedRows = ref([])

const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const onCellChange = (e) => {
  // if (c.column.property === 'moduleEname1') {
  apiGetModule2({ moduleEname1: e }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // state.dataList.forEach((item1,index)=>{

          // })
          // item.label = item.moduleCname2
          item.label = `【${item.moduleEname2}】${item.moduleCname2}`
          item.value = item.moduleEname2
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `【${item.moduleEname2}】${item.moduleEname2}`,
          value: item.moduleEname2,
        }))
        // 找到选定的行并更新其 moduleEname1 选项
        const selectedRow = tableRef.value.cloneTableData.find((row) => row.moduleEname1 === e)

        if (selectedRow) {
          selectedRow.moduleEname1Options = newArray
        }

        //  arr1.value=newArray
        // state.dataList = state.dataList.map((item) => ({
        //   ...item,
        //   moduleEname1Options:newArray , // 添加新属性
        // }));
        // const selectedRowIndex = state.dataList.findIndex((row) => row.project === e);
        //   if (selectedRowIndex !== -1) {
        //     arr1.value[selectedRowIndex] = newArray;
        //   }

        // arr1.value=newArray
        // state.dataList
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiRequestPost('/rm2/pageMaint/query', state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.formId) ids.push(item?.formId)
    })
  isTableLoading.value = true
  apiRequestPost('/rm2/pageMaint/delete', ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow1 = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  postShow.value = true
  //   let ids = []
  //   Array.isArray(checkedRows.value) &&
  //     checkedRows.value.forEach((item: any) => {
  //       if (item?.formId) ids.push(item?.formId)
  //     })
  //   isTableLoading.value = true
  //   apiRequestPost('/rm2/pageMaint/delete', ids)
  //     .then((res) => {
  //       isTableLoading.value = false
  //       searchFn()
  //     })
  //     .catch((error: any) => {
  //       isTableLoading.value = false
  //     })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
// const globalMethod: any = inject('globalMethod')
const handleAction = (item, rowData) => {
  // console.log('$Button----', proxy.$Button('delete'))
  // globalMethod('777')
}
const arr2 = ref([])
const getProjectname = () => {
  apiGetfrontPrjMaint().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `【${item.appEname}】${item.appCname}`
          item.value = item.appEname
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `【${item.appEname}】${item.appCname}`,
          value: item.appEname,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = newArray
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
const arr3 = ref([])
const getProjectname1 = () => {
  apiGetlistAllModule1().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `【${item.moduleEname1}】${item.moduleCname1}`
          item.value = item.moduleEname1
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `【${item.moduleEname1}】${item.moduleCname1}`,
          value: item.moduleEname1,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr3.value = newArray
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
onMounted(() => {
  getProjectname()
  getProjectname1()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style></style>
